<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>实现一个自定义组件例子</title>
		<script src="https://unpkg.com/vue/dist/vue.js"></script>
	</head>
	<body>
		<div id="app">
			<cms-box @func="save"></cms-box>
			<hr/>
			
			<p v-for="item in datas" :key="item.id">
				评论人:{{item.userName}},{{item.content}}
			</p>
		</div>
		<!-- 评论 -->
		<template id="cms">
			<span>
				评论人:<input type="text" v-model="userName"/><br/>
				评论内容:<textarea v-model="content"></textarea><br/>
				<input type="button" value="发表" @click="send">
			</span>
		</template>
	</body>
	
	<script>
		var cmsbox = {
			template:"#cms",
			data(){
				return {
					userName:"",
					content:""
				}
			},
			methods:{
				send(){
					console.log("userName:"+this.userName+",content:"+this.content);
					if(this.userName == "" || this.userName == null){
						alert("评论人不能为空");
						return 
					}
					var myData = {"id":Date.now(),"userName":this.userName,"content":this.content};
					this.$emit("func",myData);
					this.userName = "";
					this.content = "";
				}
			}
		};
		var vue = new Vue({
			el:"#app",
			data:{
				datas:[
					{"id":Date.now(),"userName":"张三","content":"我是张三丰的张三"},
					{"id":Date.now(),"userName":"李四","content":"我是李四光的李四"},
				]
			},
			methods:{
				save(myData){
					console.log(myData);
					this.datas.push(myData);
					localStorage.setItem("cms", JSON.stringify(this.datas));
				}
			},
			components:{
				"cms-box":cmsbox
			},
			created:function(){
				//完成了 data 数据的初始化，el没有
				var obj = localStorage.getItem("cms");
				this.datas = JSON.parse(obj);
			}
		});
	</script>
</html>
